package com.wing.oauth2.details.userdetails.warehouse;

import com.wing.common.enums.AuthMethodEnum;
import com.wing.common.utils.JsonResult;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserAuthVO;
import com.wing.warehouse.feign.WarehouseUserClient;
import com.wing.warehouse.model.response.SelContactInfoAuthVO;
import com.wing.warehouse.model.response.WarehouseUserAuthVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 系统用户体系业务类
 *
 * @author
 */
@Service("warehouseUserDetailsService")
@Slf4j
@RequiredArgsConstructor
public class WarehouseUserDetailsServiceImpl implements UserDetailsService {

    private final WarehouseUserClient warehouseUserClient;

    /**
     * 用户名或手机号加载用户信息
     *
     * @param username 用户名或手机号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        JsonResult<SelContactInfoAuthVO> userResult = warehouseUserClient.findUserByUsername(username);
        if(!JsonResult.hasData(userResult)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return this.buildUserDetails(userResult.getData(), AuthMethodEnum.USERNAME);
    }



    /**
     * 构建用户详细信息
     *
     * @param user 系统用户
     * @return 用户详细对象
     */
    private UserDetails buildUserDetails(SelContactInfoAuthVO user, AuthMethodEnum methodEnum) {
        WarehouseUserDetails userDetails = new WarehouseUserDetails(user);
        userDetails.setAuthMethod(methodEnum.getValue());
        return userDetails;
    }

}
